<?php

namespace app\controller\admin\sky;

use app\model\admin\sky\SkyCandleData;
use app\model\admin\sky\SkyCandleDetail;
use app\model\admin\sky\SkyCandle;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;
use think\response\Json;

/**
 * Class Candle
 * @package app\controller\admin\sky
 */
class Candle extends Backend
{
    /**
     *
     * @var Candle
     */
    protected $model;
    protected $hasSoftDel=0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public $orderRule = [ 'date' => 'desc'];

    protected $typeName =[
      1 => '今日大蜡烛',
        2=>'季节大蜡烛'
    ];
    public function _initialize()
    {
        $this->model = new SkyCandle();
    }


    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $allData = $this->request->param('all_data');
        $post = $this->request->param();
        $typeName = $this->typeName;
        if(isset($post['search_param']['type']['value'])&&!empty($post['search_param']['type']['value'])){
            $candle_data_ids = (new SkyCandleData())->where("type",$post['search_param']['type']['value'])->column("id");
            $candle_ids = (new SkyCandleDetail())->whereIn("candle_data_id",$candle_data_ids)->column("candle_id");
            $where[] = [
                'id',
                'in',
                $candle_ids
            ];
        }
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data  = $this->model->with("candleData")->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item){
                $types = array_unique(array_column($item['candleData'],"type"));
                array_walk($types,function (&$it)use($typeName){
                    $it = $typeName[$it];
                });
                $item['type_name'] = implode(",",$types);
                $item['area'] = array_column($item['candleData'],"area");
                if(!empty($item['area'])){
                    $item['area'] = implode(", ",array_unique($item['area']));
                }else{
                    $item['area'] = "";
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        try {
            $post     = $this->request->post();
            if(empty($post['date'])){
                throw new \Exception('请选择日期');
            }
            Db::startTrans();
            $saveData = [
                'date' => $post['date'],
                'sort' => 1,
                'type' => 0,
                'img' => "废弃",
                'area' => "废弃",
                'create_time' => time(),
            ];

            $id = (new SkyCandle())->insertGetId($saveData);
            if (!$id) throw new \Exception('保存失败');
            $candle_data_list =[];
            if(!is_array($post['candle_data_ids']))$post['candle_data_ids'] = array_unique(explode(",",$post['candle_data_ids']));
            if(count($post['candle_data_ids'])>0){
                foreach ($post['candle_data_ids'] as $item){
                    $candle_data_list[] =[
                        'candle_id'=>$id,
                        'candle_data_id'=>$item,
                    ];
                }
            }
            if(count($candle_data_list)>0)(new SkyCandleDetail())->insertAll($candle_data_list);
            Db::commit();
            $this->clearCache();
            return $this->success('操作成功');
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $id = $this->request->param('id');
        $post = CommonFun::filterPostData($this->request->post());
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if(empty($post['date'])){
            throw new \Exception('请选择日期');
        }

        $row->date = $post['date'];
        try {
            Db::startTrans();
            $save = $row->save();
            if ($save === false) throw new \Exception('保存失败');
            $candle_detail_model = new SkyCandleDetail();
            $candle_detail_model->where("candle_id",$id)->delete();
            $candle_data_list =[];
            if(!is_array($post['candle_data_ids']))$post['candle_data_ids'] = array_unique(explode(",",$post['candle_data_ids']));
            if(count($post['candle_data_ids'])>0){
                foreach ($post['candle_data_ids'] as $item){
                    $candle_data_list[] =[
                        'candle_id'=>$id,
                        'candle_data_id'=>$item,
                    ];
                }
            }
            if(count($candle_data_list)>0)$candle_detail_model->insertAll($candle_data_list);
            $this->clearCache();
            Db::commit();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }



    public function info(){
        $id = $this->request->param('id');
        $candle = $this->model->where('id',$id)->find()->toArray();
        $candle['candle_data_ids'] = implode(",",(new SkyCandleDetail())->where('candle_id',$id)->column("candle_data_id"));
        return $this->success('获取成功', $candle);
    }
}